package com.lmaos.allcontrol.beancontrol.class_;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;



public class ClassLoaderUtils {
	/** 加载进入用户主 classloader
	 * 
	 * @param buf
	 * @return
	 */
	public static Class loadSysClass(byte[] buf){
		try {
			ClassLoader classLoader = ClassLoaderUtils.class.getClassLoader();
			Class classLoaderClass = MySysClassLoader.class.getSuperclass();
			Method m = classLoaderClass.getDeclaredMethod("defineClass", byte[].class,int.class,int.class);
			m.setAccessible(true);
			return (Class) m.invoke(classLoader, buf,0,buf.length);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public static Class loadSysClass(InputStream in){
		if(in == null){
			return null;
		}
		try {
			byte[] b = new byte[in.available()];
			in.read(b);
			return loadSysClass(b);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally{
			try {
				in.close();
			} catch (Exception e2) {
			}
		}
	}
	public static URL getURL(File file){
		try {
			if(file.exists()){
					return file.toURI().toURL();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	private final static URL[] EMUTLS={};
	public static URL[] getClasspathFileURLs(URL[] urls,File classpath){
		
		URL[]curls = getClasspathFileURLs(classpath);
		if(urls == null){
			urls = EMUTLS;
		}
		if(curls.length == 0){
			return urls;
		}
		URL[] nurls = new URL[urls.length+curls.length];
		System.arraycopy(urls, 0, nurls, 0, urls.length);
		System.arraycopy(curls, 0, nurls, urls.length, curls.length);
		return nurls;
	}
	public static URL[] getClasspathFileURLs(File classpath){
		if(classpath==null||!classpath.exists()){
			return EMUTLS;
		}
		URL pUrl = getURL(classpath);
		if(classpath.isFile()){
			if(pUrl !=null ){
				return new URL[]{pUrl};
			}
		}else{
			List<File> jarfiles = new ArrayList<File>();
			List<File> dirfiles = new ArrayList<File>();
			dirfiles.add(classpath);
			for (int i = 0; i < dirfiles.size(); i++) {
				File dirfile = dirfiles.get(i);
				File[] subfiles = dirfile.listFiles();
				for (File subfile : subfiles) {
					if(subfile.isDirectory()){
						dirfiles.add(subfile);
					}else if(subfile.getAbsolutePath().endsWith(".jar")){
						jarfiles.add(subfile);
					}
				}
			}
			URL[] urls = new URL[jarfiles.size()+1];
			for (int i = 0; i < jarfiles.size(); i++) {
				urls[i+1] = getURL(jarfiles.get(i));
			}
			urls[0] = pUrl;
			return urls;
		}
		return EMUTLS;
	}
}
